package com.gaofans.vertx.boot.web.config;

import com.gaofans.vertx.boot.common.verticle.VerticleInstanceScope;
import com.gaofans.vertx.boot.web.annotation.HttpHandler;
import com.gaofans.vertx.boot.web.handler.HttpHandlerPosition;
import com.gaofans.vertx.boot.web.template.FreeMarkerEngineFactory;
import com.gaofans.vertx.boot.web.template.TemplateEngineFactory;
import com.gaofans.vertx.boot.web.utils.HttpHandlerOrder;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.common.template.TemplateEngine;
import io.vertx.ext.web.handler.TemplateHandler;
import io.vertx.ext.web.templ.freemarker.FreeMarkerTemplateEngine;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author GaoFans
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({FreeMarkerTemplateEngine.class})
@ConditionalOnMissingBean(TemplateEngineFactory.class)
@AutoConfigureBefore(VertxWebAutoConfig.class)
public class FreemarkerTemplateEngineAutoConfig {

    @Bean
    public TemplateEngineFactory freemarkerEngineFactory(Vertx vertx){
        return new FreeMarkerEngineFactory(vertx);
    }

    @Bean
    @ConditionalOnBean(TemplateEngineFactory.class)
    @ConditionalOnMissingBean(TemplateEngine.class)
    public TemplateEngine TemplateEngine(TemplateEngineFactory factory){
        return factory.create();
    }

    @HttpHandler(order = HttpHandlerOrder.FREEMARKER_TEMPLATE_HANDLER,
            position = HttpHandlerPosition.POST,
            scopeName = VerticleInstanceScope.VERTICLE_INSTANCE_NAME)
    public Handler<RoutingContext> freemarkerTemplateHandler(TemplateEngine engine){
        return TemplateHandler.create(engine);
    }

}
